import os,sys
import signal
from pynput import keyboard

g_quit_pid = None

def on_press(key):
    global g_quit_pid
    if key == keyboard.Key.esc:
        # 释放了esc 键，停止监听
        if g_quit_pid:
            os.kill(g_quit_pid, signal.SIGINT)
        return False
    # try:
    #     print('字母键： {} 被按下'.format(key.char))
    # except AttributeError:
    #     print('特殊键： {} 被按下'.format(key))


def on_release(key):
    # print('{} 释放了'.format(key))
    if key == keyboard.Key.esc:
        # 释放了esc 键，停止监听
        return False


def keyboard_listen_init(on_quit):
    # # 方式1：构造监听器对象listener
    # with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    # # 开始监听
    # # 监听启动方式1：阻断式
    # listener.join()
    global g_quit_pid
    g_quit_pid = on_quit
    # 方式2：构造监听器对象listener
    listener = keyboard.Listener(on_press=on_press, on_release=on_release)
    # 监听启动方式2：非阻断式
    listener.start()